package com.shelpe.services.tenant.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.shelpe.services.tenant.service.DictionaryService;
import com.shelpe.services.tenant.util.DicWord;
import com.shelpe.services.tenant.util.FileProcess;

@Service
public class DictionaryServiceImpl implements DictionaryService{

	private static final Logger logger = LoggerFactory.getLogger(DictionaryServiceImpl.class);
	
	@Value("${jobserver.dicFileName}")
	private String dicFileName;
	
	private static List<DicWord> dictionary;
	
	public Integer insertWord(DicWord word){
		
		if(dictionary == null || dictionary.size() == 0){
			loadDic();
		}
		
		if(!exists(word.getWord())){
			String line = word.transToString();
			FileProcess.appendToFile(dicFileName, line);
			dictionary.add(word);
			logger.info(">>>>>>>>>>>>>>>>>>>>>>>>> not exists, add");
			return 1;
		}
		
		return 0;
	}
	
	private void loadDic(){
		
		List<String> lines = FileProcess.readFileByLines(dicFileName);
		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>> lines: {}", lines.size());
		dictionary = parseLine(lines);
		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>> dictionary: {}", dictionary.size());
	}
	
	private boolean exists(String word){
		
		if(dictionary != null){
			
			for(DicWord dic : dictionary){
				if(dic.getWord().equals(word)){
					return true;
				}
			}
		}
		
		return false;
	}
	
	private List<DicWord> parseLine(List<String> lines){
		
		List<DicWord> dics = new ArrayList<DicWord>();
		if(lines != null && lines.size() > 0){
			for(String line : lines){
				DicWord  dic = new DicWord(line);
				dics.add(dic);
			}
		}
		
		return dics;
	}
}
